<template>
  <div class="component-group-activity-add-or-update">
    <el-dialog
      v-model="visible"
      :modal-append-to-body="false"
      :title="!dataForm.groupActivityId
        ? $t('groups.newJoinGroupActivity')
        : $t('groups.editGroupActivities')
      "
      :close-on-click-modal="false"
      :before-close="cancelBtn"
      width="50%"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="140px"
        @submit.prevent
      >
        <el-form-item
          :label="$t('groups.eventName')"
          prop="activityName"
        >
          <el-input
            v-model="dataForm.activityName"
            :placeholder="$t('groups.enterEventName')"
            maxlength="30"
            show-word-limit
            :disabled="dataForm.activityStatus > 2 && dataForm.activityStatus != 5
            "
            style="width: 508px;max-width:100%"
            class="groupActivity-input"
          />
        </el-form-item>
        <el-form-item
          :label="$t('group.actTime')"
          prop="startTime"
        >
          <el-date-picker
            v-model="dataForm.startTime"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
              : false
            "
            value-format="YYYY-MM-DD"
            type="date"
            class="date-picker"
            style="width:140px"
            :placeholder="$t('marketing.chooseStartTime')"
          />
          <el-time-select
            v-model="startTimeValue"
            start="00:00"
            step="00:30"
            end="23:30"
            :class="[startTimeValue ? 'select-time': '']"
            align="center"
            style="width:102px"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
              : false
            "
            :placeholder="$t('time.startTime')"
            @blur="startTimeValueChange"
          />
          <span style="margin:0 5px;width:14px;display: inline-block;">{{ $t('time.tip') }}</span>
          <el-date-picker
            v-model="dataForm.endTime"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus > 2 && dataForm.activityStatus != 5
              : false
            "
            value-format="YYYY-MM-DD"
            type="date"
            class="date-picker"
            style="width:140px"
            :placeholder="$t('marketing.chooseEndTime')"
          />
          <el-time-select
            v-model="endTimeValue"
            start="00:00"
            step="00:30"
            end="23:30"
            :class="[endTimeValue ? 'select-time': '']"
            align="center"
            style="width:102px"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus > 2 && dataForm.activityStatus != 5
              : false
            "
            :placeholder="$t('time.endTime')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('group.groupNum')"
          prop="groupNumber"
        >
          <el-input
            v-model="dataForm.groupNumber"
            type="number"
            min="2"
            max="1000000000"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
              : false
            "
            class="groupActivity-input"
            style="width: 508px;max-width:100%"
            @change="groupNumCheck"
          >
            <template #append>
              {{ $t("groups.people") }}
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('groups.groupValidityPeriod')"
          prop="groupValidTime"
        >
          <el-input
            v-model="dataForm.groupValidTime"
            type="number"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
              : false
            "
            class="groupActivity-input"
            onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
            min="0"
            style="width: 508px;max-width:100%"
          >
            <template #append>
              {{ $t("groups.minute") }}
            </template>
          </el-input>

          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('groups.tip4')"
            placement="right"
          >
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </el-form-item>
        <el-form-item
          :label="$t('groups.limitPurchase')"
          prop="hasMaxNum"
        >
          <el-radio-group
            v-model="dataForm.hasMaxNum"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
              : false
            "
          >
            <el-radio :label="0">
              {{ $t("station.close") }}
            </el-radio>
            <el-radio :label="1">
              {{ $t("groups.turnOn") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="dataForm.hasMaxNum"
          :label="$t('product.maxNum')"
          prop="maxNum"
        >
          <el-input
            v-model="dataForm.maxNum"
            type="number"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
              : false
            "
            min="1"
            max="100000000"
            class="groupActivity-input"
            @change="maxNumCheck"
          >
            <template #append>
              {{ $t("groups.memberPeople") }}
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('groups.simulation')"
          prop="hasRobot"
        >
          <div>
            <el-radio-group
              v-model="dataForm.hasRobot"
              :disabled="dataForm.activityStatus
                ? dataForm.activityStatus > 2 && dataForm.activityStatus != 5
                : false
              "
            >
              <el-radio :label="0">
                {{ $t("station.close") }}
              </el-radio>
              <el-radio :label="1">
                {{ $t("groups.turnOn") }}
              </el-radio>
            </el-radio-group>
            <div class="auxiliary-font">
              <span>{{ $t("groups.tip5") }} </span>
            </div>
          </div>
        </el-form-item>
        <!-- 团长优惠 已废弃 -->
        <!-- <el-form-item
    :label="$t('groups.groupLeaderOffer')"
    prop="hasLeaderPrice"
  >
    <el-radio-group
      :disabled="
        dataForm.activityStatus
          ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
          : false
      "
      v-model="dataForm.hasLeaderPrice"
    >
      <el-radio :label="0">{{ $t("station.close") }}</el-radio>
      <el-radio :label="1">{{ $t("groups.turnOn") }}</el-radio>
    </el-radio-group>
    <div class="auxiliary-font">{{ $t("groups.tip6") }}</div>
    <div class="auxiliary-font font-color-red">
      {{ $t("groups.tip7") }}
    </div>
  </el-form-item> -->
        <el-form-item
          :label="$t('groups.groupMode')"
          prop="hasGroupTip"
        >
          <el-radio-group
            v-model="dataForm.hasGroupTip"
            :disabled="dataForm.activityStatus
              ? dataForm.activityStatus > 2 && dataForm.activityStatus != 5
              : false
            "
          >
            <el-radio :label="0">
              {{ $t("station.close") }}
            </el-radio>
            <el-radio :label="1">
              {{ $t("groups.turnOn") }}
            </el-radio>
          </el-radio-group>
          <div class="auxiliary-font">
            {{ $t("groups.tip8") }}
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('groups.activityWarmUp')"
          prop="isPreheat"
        >
          <el-radio-group
            v-model="dataForm.isPreheat"
            :disabled="(dataForm.activityStatus
              ? dataForm.activityStatus !== 1 && dataForm.activityStatus != 5
              : false) || showEventPreview"
          >
            <el-radio :label="0">
              {{ $t("station.close") }}
            </el-radio>
            <el-radio :label="1">
              {{ $t("groups.turnOn") }}
            </el-radio>
          </el-radio-group>
          <div class="auxiliary-font">
            {{ $t("groups.tip9") }}
          </div>
        </el-form-item>
        <!-- 商品选择框 -->
        <el-form-item
          :label="$t('groups.selectProd')"
          prop="prodId"
        >
          <el-button
            v-if="!dataForm.prodId"
            class="tips-button"
            :disabled="dataForm.status == 5 && dataForm.groupActivityId != null"
            @click="selectProdHandle"
          >
            {{ $t('groups.selectProd') }}
            <el-tooltip
              :content="$t('groups.tip10')"
              placement="top"
              class="tips"
              style="position:absolute;marginLeft:3px"
            >
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-button>
          <!-- 商品 -->
          <div
            v-if="dataForm.prodId"
            style="display:flex;marginBottom:20px"
          >
            <el-card
              v-for="item in spus"
              :key="item.skuId"
              :body-style="{ padding: '0px' }"
              style="height: 160px;width: 120px;margin-right:5px"
            >
              <ImgShow
                :src="item.pic"
                :img-style="{ width: '100%', height: '104px' }"
              />
              <div class="card-prod-bottom card-prod-d">
                <span class="card-prod-name">{{ item.skuName }}</span>
                <el-button
                  v-if="!dataForm.groupActivityId"
                  type="text"
                  class="card-prod-name-buttons"
                  @click="deleteCurrentProd()"
                >
                  删除
                </el-button>
              </div>
            </el-card>
          </div>
        </el-form-item>
        <!-- 商品sku列表 -->
        <div v-if="dataForm.groupSkuList && dataForm.groupSkuList.length > 0">
          <el-table
            :data="dataForm.groupSkuList"
            border
            header-cell-class-name="table-header"
            row-class-name="table-row"
          >
            <el-table-column :label="dataForm.groupSkuList.length > 1 ? 'sku名称' : '商品名称'">
              <template #default="scope">
                <span>{{ dataForm.groupSkuList.length > 1 ? scope.row.skuName : spus[0].skuName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="活动价格">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.actPrice"
                  :disabled="!(dataForm.groupActivityId == null || dataForm.status == 2) || scope.row.status !== 1"
                  :min="0.01"
                  :step="1"
                  :max="!(dataForm.groupActivityId == null || dataForm.status == 2) || scope.row.status !== 1 ? 100000000 : scope.row.price"
                  class="groupActivity-input"
                  @change="actPriceChange(scope.$index, $event)"
                  @blur="actPriceBlur"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <div
            class="default-btn"
            size="mini"
            @click="cancelBtn()"
          >{{
            $t("crud.filter.cancelBtn")
          }}</div>
          <div
            v-if="dataForm.status !== 0 && dataForm.status !== 5 || dataForm.groupActivityId == null"
            class="default-btn primary-btn"
            type="primary"
            size="mini"
            @click="dataFormSubmit()"
          >{{
            $t("groups.submit")
          }}</div>
        </span>
      </template>
    </el-dialog>
    <!-- 商品选择弹窗  测试完之后添加这个链接  dataUrl='/group/prod/getNotGroupProdPage'-->
    <prods-select
      v-if="groupSelectProdVisible"
      ref="ProdsSelectRef"
      :is-single="true"
      :prod-type="0"
      @refresh-select-prods="selectGroupProds"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList', 'closeAddOrUpdate'])
const Data = reactive({
  visible: false,
  showEventPreview: false,
  groupSelectProdVisible: false,
  roleList: [],
  selectTime: [],
  dataForm: {
    groupActivityId: null,
    prodId: null,
    shopId: null,
    activityName: null,
    status: null,
    startTime: null,
    endTime: null,
    groupValidTime: null,
    groupNumber: null,
    hasMaxNum: 0,
    maxNum: null,
    hasRobot: 0,
    hasLeaderPrice: 0,
    isPreheat: 0,
    hasGroupTip: 1,
    groupOrderCount: null,
    groupNumberCount: null,
    createTime: null,
    updateTime: null,
    groupProds: [],
    validEndTime: [],
    groupSkuList: []
  },
  spus: [],
  isSubmit: false,
  groupProdAndSkuLists: [],
  startTimeValue: '',
  endTimeValue: ''
})

const { visible, showEventPreview, groupSelectProdVisible, dataForm, spus, startTimeValue, endTimeValue } = toRefs(Data)

const validateTime = (rule, value, callback) => {
  if ((!Data.startTimeValue || !Data.dataForm.startTime)) {
    callback(new Error($t('formData.startTimeCannotBeEmpty')))
  }
  if ((!Data.endTimeValue || !Data.dataForm.endTime)) {
    callback(new Error($t('formData.endTimeCannotBeEmpty')))
  }
  const startTime = Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00'
  const endTime = Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00'
  if (Date.parse(startTime) < Date.parse(new Date())) {
    Data.showEventPreview = true
  } else {
    Data.showEventPreview = false
  }
  if (Data.dataForm.status !== 5 && Data.endTimeValue && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  }
  if (Data.startTimeValue && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('groups.endTimeIsTooSmall')))
  } else if (Data.dataForm.status === 1 && Data.dataForm.groupActivityId && Date.parse(Data.validEndTime) > Date.parse(endTime)) {
    if (Data.endTimeValue) callback(new Error($t('groups.extendedEndTime')))
  } else {
    callback()
  }
}
const validateGroupNumber = (rule, value, callback) => {
  if (Data.dataForm.groupNumber < 2) {
    callback(new Error($t('groups.tip1')))
  } else {
    callback()
  }
}
const validateactivityName = (rule, value, callback) => {
  if (!Data.dataForm.activityName.trim()) {
    callback(new Error($t('groups.pleaseEnterEventName')))
  } else {
    callback()
  }
}
const validateGroupValidTime = (rule, value, callback) => {
  if (Data.dataForm.groupValidTime < 15) {
    callback(new Error($t('groups.tip2')))
  } else if (Data.dataForm.groupValidTime > 24 * 60) {
    callback(new Error($t('groups.tip3')))
  } else {
    callback()
  }
}

const dataRule = reactive({
  activityName: [
    { required: true, message: $t('groups.pleaseEnterEventName'), trigger: 'blur' },
    { validator: validateactivityName, trigger: 'blur' }
  ],
  maxNum: [
    { required: true, message: $t('groups.pleaseEnterEventNum'), trigger: 'blur' }
  ],
  groupNumber: [
    { required: true, message: $t('groups.pleaseEnteNumGrp'), trigger: 'blur' },
    { validator: validateGroupNumber, trigger: 'blur' }
  ],
  groupValidTime: [
    { required: true, message: $t('groups.pleaseEnterTimeGroup'), trigger: 'blur' },
    { validator: validateGroupValidTime, trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('groups.startTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ]
})

const dataFormRef = ref()
const init = (groupActivityId) => {
  Data.dataForm.groupSkuList = []
  Data.dataForm.groupActivityId = groupActivityId || null
  Data.dataForm.activityStatus = null
  Data.visible = true
  Data.isSubmit = false
  nextTick(() => {
    dataFormRef.value.resetFields()
    const datetimeRange = getDateTimeRange()
    Data.dataForm.startTime = datetimeRange.startTime
    Data.dataForm.endTime = datetimeRange.endTime
    Data.startTimeValue = datetimeRange.currentTime
    Data.endTimeValue = datetimeRange.currentTime
    if (Data.dataForm.groupActivityId) {
      http({
        url: http.adornUrl('/group/activity/info/' + Data.dataForm.groupActivityId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        Data.spus = [{
          skuName: data.prodName,
          pic: data.prodPic
        }]
        if (Date.parse(data.startTime) < Date.parse(new Date())) {
          Data.showEventPreview = true
        } else {
          Data.showEventPreview = false
        }
        Data.dataForm = data
        Data.startTimeValue = Data.dataForm.startTime ? Data.dataForm.startTime.substring(11, Data.dataForm.startTime.length - 3) : ''
        Data.endTimeValue = Data.dataForm.endTime ? Data.dataForm.endTime.substring(11, Data.dataForm.endTime.length - 3) : ''
        Data.dataForm.startTime = getParseTime(Data.dataForm.startTime, '{y}-{m}-{d}')
        Data.dataForm.endTime = getParseTime(Data.dataForm.endTime, '{y}-{m}-{d}')
        Data.validEndTime = data.endTime
      })
    }
  })
}

const startTimeValueChange = () => {
  const startTime = Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00'
  if (Date.parse(startTime) < Date.parse(new Date())) {
    Data.showEventPreview = true
  } else {
    Data.showEventPreview = false
  }
}

// 表单提交
const dataFormSubmit = Debounce(() => {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      if (Data.isSubmit) {
        return false
      }
      if (!Data.dataForm.prodId) {
        return ElMessage.error('请选择商品')
      }
      const startTime = Data.dataForm.startTime
      const endTime = Data.dataForm.endTime
      Data.dataForm.startTime = Data.dataForm.startTime && Data.startTimeValue ? Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00' : ''
      Data.dataForm.endTime = Data.dataForm.endTime && Data.endTimeValue ? Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00' : ''
      Data.isSubmit = true
      http({
        url: http.adornUrl('/group/activity'),
        method: Data.dataForm.groupActivityId ? 'put' : 'post',
        data: http.adornData(Data.dataForm)
      }).then(() => {
        Data.selectTime = []
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            Data.visible = false
            Data.isSubmit = false
            emit('refreshDataList')
          }
        })
      }).catch((e) => {
        Data.isSubmit = false
      })
      Data.dataForm.startTime = startTime
      Data.dataForm.endTime = endTime
    }
  })
})

const ProdsSelectRef = ref()
// 选择商品操作
const selectProdHandle = () => {
  Data.groupSelectProdVisible = true
  nextTick(() => {
    ProdsSelectRef.value.init(Data.dataForm.groupProds)
  })
}

// 选商品回调
const selectGroupProds = (prods) => {
  if (prods) {
    Data.dataForm.prodId = prods.prodId
    let prodIds = []
    Data.dataForm.groupProds = prods
    Data.spus = [{
      skuName: prods.prodName,
      pic: prods.pic
    }]
    prodIds.push(prods.prodId)
    getProdAndSkuListsByProdIds(prodIds)
    prodIds = []
  }
}

const groupNumCheck = () => {
  let maxNum = Math.round(Data.dataForm.groupNumber)
  if (!maxNum) {
    maxNum = 2
  } else if (maxNum < 2) {
    maxNum = 2
  } else if (maxNum > 500) {
    maxNum = 500
  }
  Data.dataForm.groupNumber = maxNum
}

const maxNumCheck = () => {
  let maxNum = Math.round(Data.dataForm.maxNum)
  if (!maxNum) {
    maxNum = 1
  } else if (maxNum < 1) {
    maxNum = 1
  } else if (maxNum > 1000000000) {
    maxNum = 1000000000
  }
  Data.dataForm.maxNum = maxNum
}

const { proxy } = getCurrentInstance()
// 通过商品id列表，查询所有的对应的sku列表
const getProdAndSkuListsByProdIds = (prodIds) => {
  if (prodIds) {
    http({
      url: http.adornUrl('/sku/getAllSkuList'),
      method: 'get',
      params: {
        prodId: prodIds
      }
    }).then(({ data }) => {
      Data.dataForm.groupSkuList = Data.dataForm.groupSkuList || []
      for (let index = 0; index < data.length; index++) {
        const obj = {
          actPrice: data[index].price,
          // groupSkuId: item.,
          pic: data[index].pic,
          price: data[index].price,
          properties: data[index].properties,
          sellNum: data[index].actualStock - data[index].stocks,
          skuId: data[index].skuId,
          skuName: data[index].skuName,
          status: data[index].status
        }
        Data.dataForm.groupSkuList.push(obj)
      }
      proxy.$forceUpdate()
    })
  }
}

/**
* 删除商品
*/
const deleteCurrentProd = () => {
  Data.spus = []
  Data.dataForm.groupSkuList = []
  Data.dataForm.prodId = null
}

// 关闭对话框
const cancelBtn = () => {
  deleteCurrentProd()
  emit('closeAddOrUpdate')
  Data.visible = false
}

const actPriceBlur = (e) => {
  Data.dataForm.groupSkuList.forEach(item => {
    if (!item.actPrice) item.actPrice = 0.01
  })
}

// 保留两位小数
const actPriceChange = (index, value) => {
  Data.dataForm.groupSkuList[index].actPrice = value.toFixed(2)
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.component-group-activity-add-or-update {

  :deep(.el-form-item__content){
    display: block;
  }
  .date-picker {
    width: 60%;
  }

  .card-prod-bottom {
    position: relative;
    text-align: left;

    .card-prod-name {
      margin: auto;
      padding: 0 6px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 118px;
      display: inline-block;
    }

  }

  .groupActivity-input {
    width: 60%;
  }

  .auxiliary-font {
    font-size: 12px;
    color: #cbc0cb;
    line-height: 20px;
  }

  .card-prod-bottom {
    display: flex;
    justify-content: space-around;
  }

  .card-prod-name {
    margin: auto;
    padding: 0 6px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 118px;
    display: inline-block;
    line-height: 50px;
  }

  .card-prod-name-buttons {
    padding-right: 5px;
    height: 50px;
  }

  .tips-button {
    padding-right: 26px;
  }

  :deep(.el-select .el-input__suffix-inner){
      display: none;
    }
  .select-time:hover :deep(.el-input__suffix-inner){
    display: inline-flex;
  }
}
</style>
